(function ($) {
	var me = {};
	window.Form = Class.create({
		// 继承的父类
		Extends: FormElement,
		// 混入的集合
		//Mixes: EventMixin,
		// 静态方法
		//Statics: {},
		// 构造
		constructor: function(element, options){
			this.element = $(element);
			me = this;
			$.each(options,function(k,v){
				if( v == undefined && v == null ) return true;
				if( typeof v === 'object' ) {
					$.extend(me.get(k),v);
				} else {
					me.set(k,v);
				}
			});
		},
		// 主键字段
		pkField: "id",
		// 请求地址
		modularPath: {
			editUrl: "/find",
			insertUrl: "/insert",
			updateUrl: "/update",
		},
		// 表单元素配置
		FormOption: [],
		// 表单元素模板
		FormElementTpl: '',
		// 创建表单元素
		createFormElement: function(){
			var formElementSettings = {
				prefixId: me.prefixId,
				apiPathPrefix: me.apiPathPrefix,
				elementOption: me.FormOption,
				//elementTpl: me.FormElementTpl
			};
			// 修改时获取数据
			var params = me.getUrlParams();
			if( params[me.pkField] != undefined && params[me.pkField] != '' ) {
				me.editAjaxOption.url = me.getUrl(me.modularPath.editUrl);
				me.editAjaxOption.data = params;
				$.ajax(me.editAjaxOption);
				formElementSettings.editData = me.editData;
			}
			var formElement = me.element.formElement(formElementSettings);
			me.validateOption.rules = formElement.data('formElement').get('validateRules');
			me.validateOption.messages = formElement.data('formElement').get('validateMessages');
		},
		// 修改的数据
		editData: {},
		// 按钮列表
		buttons: ['back','submit','reset'],
		// 按钮背景div元素
		buttonBackdrop: '<div class="space-4"></div>' +
						'<div class="clearfix form-actions">' +
							'<div class="col-md-offset-3 col-md-9">' +
							'{0}' +
							'</div>' +
						'</div>',
		// 按钮div元素
		buttonTpl: '<button class="{3}" id="{0}" type="button">' +
						'<i class="ace-icon fa {1} bigger-110"></i>' +
						'{2}' +
					'</button>',
		// 返回按钮
		backButton:{
			enable: true,
			id: "btnBack",
			title: '返回',
			icon: "fa-reply",
			className: "btn",
			buttonTpl: "",
		},
		// 返回操作
		backAction: function(){
			window.history.go(-1);
		},
		// 提交按钮
		submitButton: {
			enable: true,
			pk: 'id',
			id: "btnSubmit",
			title: '提交',
			icon: "fa-check",
			className: "btn btn-info",
			buttonTpl: "",
		},
		// 提交操作
		submitAction: function(){
			var $form = me.element;
			var pkValue = $form.find("input[name=" + me.pkField + "]").val();
			var url = ( pkValue == undefined || pkValue == '' ) ? me.modularPath.insertUrl : me.modularPath.updateUrl;
			var enctype = $form.attr('enctype');
			var formData = $form.serializeArray();
			// 是否有文件上传
			if( enctype == "multipart/form-data" ) {
				formData = new FormData($form[0]);
			} else  {
				delete me.submitAjaxOption.contentType;
				delete me.submitAjaxOption.processData;
			}
			me.submitAjaxOption.url = me.getUrl(url);
			me.submitAjaxOption.data = formData;
			// 表单提交
			$form.submit();
		},
		// 重置按钮
		resetButton: {
			enable: true,
			id: "btnReset",
			title: '重置',
			icon: "fa-undo",
			className: "btn",
			buttonTpl: "",
		},
		// 重置操作
		resetAction: function(){
			var $form = me.element;
			$form[0].reset();
		},
		// 创建按钮
		createButtons: function(){
			var html = '', $form = me.element;
			$.each(me.buttons,function(k,v){
				var val = me[v + 'Button'];
				// 未启用则退出本次循环
				if( !val['enable'] ) return true;
				var _id = val.id || "", _icon = val.icon || "", _title = val.title || "", _className = val.className || "";
				html += val.buttonTpl != "" ? val.buttonTpl.format(_id,_icon,_title,_className) : me.buttonTpl.format(_id,_icon,_title,_className);
				html += '&nbsp; &nbsp; &nbsp;';
			});
			html = me.buttonBackdrop.format(html);
			me.element.append(html);
			// 绑定操作事件
			$.each(me.buttons,function(k,v){
				var val = me[v + 'Button'];
				if( !val['enable'] ) return true;
				var _event = me[v + 'Action'] || function(){};
				$("#" + val.id).on('click', function(){
					_event();
				});
			});
		},
		// 获取修改页数据 - 异步请求参数
		editAjaxOption: {
			type: "get",
			dataType: "json",
			url: "",
			data: "",
			async: false,
			success: function(data){
				me.editSuccess(arguments);
				$.extend(me.editData, data.result, me.urlParams);
			},
			error: function(data){
				me.editError(arguments);
			}
		},
		// 获取修改页数据加载成功
		editSuccess: function(args){},
		// 获取修改页数据加载失败
		editError: function(args){},
		// 提交数据 - 异步请求参数
		submitAjaxOption: {
			type: "post",
			dataType: "json",
			url: "",
			data: "",
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function(data){
				me.submitSuccess(data);
			},
			error: function(data){
				me.submitError(arguments);
			}
		},
		// 提交数据加载成功
		submitSuccess: function(data){
			me.showMsg(data['message']);
			if( data['isOk'] == 1 ) {
				window.history.go(-1);
			}
		},
		// 提交数据加载失败
		submitError: function(args){
			console.log(args);
		},
		// 创建Element
		load: function(data){
			me.beforeLoad();
			me.createFormElement();
			me.createButtons();
			me.afterLoad();
		},
		// 加载数据前操作
		beforeLoad: function(){},
		// 加载数据之后操作
		afterLoad: function(){
			var $form = me.element;
			$form.validate(me.validateOption);
		},
		// 验证参数
		validateOption: {
			rules: {},
			messages: {},
			submitHandler: function (form) {
				// 表单提交
				$.ajax(me.submitAjaxOption);
			},
		},
		// 返回访问地址
		getUrl: function(url){
			me = this;
			url = ( url.indexOf(me.prefixId) == -1 ? '/' + me.prefixId : '') + url;
			url = ( url.indexOf("//") == -1 ? me.apiPathPrefix : '') + url;
			return url;
		},
	});
    /**
     * 扩展 Jquery 对象为 Form
     * @param option
     */
	$.fn.form = function(option){
		return this.each(function () {
			var $this = $(this),
			   data = $this.data('form'),
			   options = typeof option === 'object' && option;
			if (!data)  {
				$this.data('form', (data = new Form(this, $.extend({}, options))));
			}
			if (typeof option == 'string') {
				data[option]();
			}
			if(data.autoLoad){
				data.load();
			}
		});
	};
	// 属性返回对创建此对象的函数的引用
	$.fn.form.Constructor = Form;

})(jQuery);
